package com.rhino.magiccubecircle.http

import com.rhino.base.extension.HTTP_LOG_TAG
import com.rhino.base.extension.printELog
import com.rhino.base.extension.printWLog
import com.rhino.xchat.http.ErrorCode
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import org.json.JSONObject
import java.nio.charset.StandardCharsets


/**
 * @author LuoLin
 * @since Create on 2024/9/29.
 */
class TokenInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        return handleErrorCode(chain.proceed(chain.request()))

//        BaseResponse baseResponse = BaseResponse.format(responseStr);
//        if (baseResponse != null) {
//            if (baseResponse.isTokenExpired()) {
//                // TOKEN过期，同步请求方式，获取最新的Token
//                String json = FileUtils.readFile(new File(HeaderComDataBean.TOKEN_DATA_FILE_PATH).getPath());
//                Cache.headerComDataBean = JsonUtils.format(json, HeaderComDataBean.class);
//                // 使用新的Token，创建新的请求
//                LogUtils.w("重新获取token成功：" + Cache.headerComDataBean);
//                Map<String, String> headers = HeaderInterceptor.createHeader(request);
//                Request.Builder newBuilder = request.newBuilder();
//                for (Map.Entry<String, String> entry : headers.entrySet()) {
//                    newBuilder.removeHeader(entry.getKey());
//                    newBuilder.addHeader(entry.getKey(), entry.getValue());
//                }
//                return chain.proceed(newBuilder.build());
//            }
//        }
//        return response
    }

    private fun handleErrorCode(response: Response): Response {
        /*
          不能直接使用response.body().string()的方式获取请求返回，
          因为response.body().string()之后，response中的流会被关闭，程序会报错
          我们需要创建出一个新的response进行处理
        */
        val responseBody = response.peekBody((1024 * 1024).toLong())
        val responseStr = responseBody.string()
//        var baseResponse = BaseResponse<Any>()
//        kotlin.runCatching {
//            baseResponse =
//                GsonUtils.fromJson(responseStr, BaseResponse::class.java) as BaseResponse<Any>
//        }
//        when (baseResponse.code) {
//            ErrorCode.CODE_0007.code -> {
//                // 登录成功,补充信息为空
//                val loginInfo = ResLoginInfo()
//                loginInfo.token = ((baseResponse.data as? LinkedTreeMap<*, *>)?.get("token")
//                    ?: "").toString()
//                Cache.saveLoginInfo(loginInfo)
//                TheRouter.build(RouteConstant.COMPLETE_USER_INFO_ACTIVITY)
//                    .withInAnimation(R.anim.welcome_activity_open_enter)
//                    .withOutAnimation(R.anim.welcome_activity_close_exit)
//                    .navigation(callback = object : NavigationCallback() {
//                        override fun onArrival(navigator: Navigator) {
//                            ActivityUtils.finishToActivity(
//                                CompleteUserInfoActivity::class.java,
//                                false
//                            )
//                        }
//                    })
//                return newSuccessResponse(response)
//            }
//
//            ErrorCode.CODE_0008.code, ErrorCode.CODE_0009.code -> {
//                // 同一账户不能在多个设备登录，请及时修改密码
//                baseResponse.msg?.toast()
//                Cache.logout()
//                TheRouter.build(RouteConstant.LOGIN_ACTIVITY)
//                    .withInAnimation(R.anim.welcome_activity_open_enter)
//                    .withOutAnimation(R.anim.welcome_activity_close_exit)
//                    .navigation(callback = object : NavigationCallback() {
//                        override fun onArrival(navigator: Navigator) {
//                            ActivityUtils.finishToActivity(
//                                LoginActivity::class.java,
//                                false
//                            )
//                        }
//                    })
//                return newSuccessResponse(response)
//            }
//        }
        return response
    }

    private fun newSuccessResponse(response: Response): Response {
        var respBytes = byteArrayOf()
        // 修改返回的数据
        try {
            val jSONObject = JSONObject()
            jSONObject.put("code", ErrorCode.CODE_0000.code)
            jSONObject.put("msg", ErrorCode.CODE_0000.msg)
            jSONObject.put("data", null)
            respBytes = jSONObject.toString().toByteArray(StandardCharsets.UTF_8)
            printWLog(HTTP_LOG_TAG, "new responseStr: $jSONObject")
        } catch (e: Exception) {
            printELog(HTTP_LOG_TAG, e.toString())
        }
        // 将新的数据放入Response中
        val mediaType = response.body!!.contentType()
        return response.newBuilder().body(ResponseBody.create(mediaType, respBytes))
            .build()
    }
}